import axios from 'axios'
import { Message, Loading } from 'element-ui'
import Router from './../router'

let loadingInstance
const url = window.basicData.apiPrefix
let noLoadings = [
    '/api/v1/monitor-data/detection' // 不要loading 的icon
]
const modules = {
    // 多个请求同时进行
    allAxios: function (obj) {
        let arrs = []
        Object.keys(obj).forEach((key) => {
            arrs.push(obj[key])
        })
        return axios.all(arrs)
    }
}
// 开发环境设置axios.defaults.withCredentials 为true，否为不允许带cookie
if (process.env.NODE_ENV === 'development') {
    axios.defaults.withCredentials = true
}
// 请求拦截器 例
axios.interceptors.request.use(
    config => {
        console.log(config)
        // const token = getCookie('session')
        const urlSplit = config.url.split(url)
        const indexofs = noLoadings.indexOf(urlSplit[1])
        config.data = JSON.stringify(config.data)
        config.headers = {
            'Content-Type': 'application/json;charset=utf-8'
        }
        let isLoading = true
        if (indexofs !== -1) {
            isLoading = false
        }
        // if (token) {
        //     config.params = {'token': token}
        // }
        if (isLoading) {
            loadingInstance = Loading.service({
                fullscreen: true,
                lock: false,
                text: '',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, 0)'
            })
        }
        return config
    },
    err => {
        if (loadingInstance) {
            loadingInstance.close()
        }
        Message({ type: 'error', message: err })
        return Promise.reject(err)
    }
)

// 响应拦截器
axios.interceptors.response.use(
    function (response) {
        if (loadingInstance) {
            loadingInstance.close()
        }
        if (response.data.code === 404) {
            Router.push({ path: '/login' })
        }
        return Promise.resolve(response)
    },
    function (error) {
        console.log(error)
        if (loadingInstance) {
            loadingInstance.close()
        }
        Message({type: 'error', message: (error.response && error.response.data.msg) || '请求失败,请尝试刷新页面'})
        return Promise.reject(error)
    }
)

// 合并目录下的所有文件除去index,resource,api
const files = require.context('.', false, /\.js$/)
files.keys().forEach((key) => {
    if (key === './index.js' || key === './resource.js' || key === './api.js') return
    modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})

export default modules
